package com.lkd.job;

import com.lkd.common.VMSystem;
import com.lkd.entity.UserEntity;
import com.lkd.service.UserService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author : Bing
 * @Date 2023/3/4 16:43
 */
@Component
public class UserJob {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @XxlJob("workCountInitJobHandler")
    public ReturnT<String> workCountInitJobHandler(String param) {

        List<UserEntity> userEntityList = userService.list();

        //过滤掉管理员，如果某个地区要归零，只取某个地区
        List<UserEntity> collect = filterAdminAndParm(param, userEntityList);

        collect.forEach(each -> {
            String redisKey = VMSystem.REGION_TASK_KEY_PREF
                    + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "."
                    + each.getRegionId() + "."
                    + each.getRoleCode();

            redisTemplate.opsForZSet().add(redisKey, each.getId(), 0);
            redisTemplate.expire(redisKey, Duration.ofDays(1));
        });


        return ReturnT.SUCCESS;
    }

    private List<UserEntity> filterAdminAndParm(String param, List<UserEntity> userEntityList) {
        List<UserEntity> collect;
        if (StringUtils.isBlank(param)) {
            collect = userEntityList.stream()
                    .filter(user -> !Objects.equals(user.getRoleCode(), "1001"))
                    .collect(Collectors.toList());
        } else {
            collect = userEntityList.stream()
                    .filter(user -> !Objects.equals(user.getRoleCode(), "1001")
                            && user.getRegionId() == Integer.parseInt(param))
                    .collect(Collectors.toList());
        }
        return collect;
    }

}
